﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Security.Cryptography;

namespace Group16.Class_Library
{
    public class CryptoText
    {
        public readonly byte[] Bytes = { 0x39, 0x38, 0x14, 0x05, 0x68 };
        private byte[] _pwd;
        private MemoryStream _ms;
        private CryptoStream _cs;
        public byte []Password
        {
            get { return _pwd; }
        }
        private MemoryStream MStream
        {
            get { return _ms; }
            set { _ms = value; }
        }
        private CryptoStream CStream
        {
            get { return _cs; }
            set { _cs = value; }
        }
        public CryptoText(string pass)
        {
            if (String.IsNullOrEmpty(pass))
                throw new ArgumentException("pass is empty");
            _pwd = Encoding.UTF8.GetBytes(pass);
        }
        public string ConvertText(string text, bool isEncrypt)
        {
            byte[] bytes = isEncrypt ? Encoding.UTF8.GetBytes(text) : Convert.FromBase64String(text);
            MStream = new MemoryStream();
            SymmetricAlgorithm alg = SymmetricAlgorithm.Create();
            PasswordDeriveBytes pass = new PasswordDeriveBytes(Password, Bytes);
            alg.Key = pass.GetBytes(alg.KeySize / 8);//chu y
            alg.IV = pass.GetBytes(alg.BlockSize / 8);

            ICryptoTransform transform = isEncrypt ? alg.CreateEncryptor() : alg.CreateDecryptor();
            CStream = new CryptoStream(MStream, transform, CryptoStreamMode.Write);
            CStream.Write(bytes, 0, bytes.Length);
            CStream.FlushFinalBlock();
            byte[] result = MStream.ToArray();
            return isEncrypt ? Convert.ToBase64String(result) : Encoding.UTF8.GetString(result);
        }
    }
}
